<?php
declare (strict_types=1);

namespace app\api\controller\notify;

use app\common\controller\IndexBase;
use app\common\helper\NetPay;
use app\common\helper\Printer;
use app\common\model\Pay;
use think\facade\Db;
use think\facade\Env;

class Index extends IndexBase
{

    public function notify()
    {
        $pay = new NetPay();
        return $pay->notify();
    }
    
    public function refund_notify()
    {
        $pay = new NetPay();
        return $pay->refund_notify();
    }
    
    public function pay()
    {
        $env = Env::get('APP_DEBUG');
        if (!$env) {
            return '';
        }
        $order = Pay::where("id", $this->data['id'])->find();
        if ($order) {

            Db::startTrans();
            try {
                $out_trade_no = $order->order_no;
                $order->pay_time = time();
                $order->status = 1;
                $order->save();
                if ($order->type == 'goods') {
                    $goodsOrder = \app\common\model\Order::where("order_no", $out_trade_no)->find();
                    if ($goodsOrder) {
                        $goodsOrder->pay_status = 1;
                        $goodsOrder->status = 200;
                        $goodsOrder->save();
                        $print = new Printer();
                        $print->printer($goodsOrder);
                        LegworkLogic::createOrderToLegwork($goodsOrder);
                    }
                }
                if ($order->type == 'delivery') {
                    $goodsOrder = \app\common\model\DeliveryOrder::where("order_no", $out_trade_no)->find();
                    if ($goodsOrder) {
                        $goodsOrder->status = 1;
                        $goodsOrder->save();
                    }
                }
                if ($order->type == 'legwork') {
                    $goodsOrder = LegworkOrder::where("id",$order->order_id)->find();
                    if ($goodsOrder) {
                        $goodsOrder->status = 1;
                        $goodsOrder->save();
                    }
                }
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                dump($exception->getMessage());
            }
        }
    }
}
